<template>
  <div class="chat-container">
    <!-- 左侧联系人列表 -->
    <div class="contact-list" v-if="contactList.length>0">
      <h2 class="list-title">联系人</h2>
      <div
          v-for="user in contactList"
          :key="user.userId"
          class="contact-item"
          :class="{ active: currentChat?.userId === user.userId }"
          @click="selectChat(user)"
      >
        <div class="avatar">
          <image-preview :src="user.avatar"/>
        </div>
        <div class="info">
          <h3>{{ user.userName }}</h3>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area" v-if="contactList.length>0">
      <div class="chat-header">
        <div class="header-left">
          <h2>{{ currentChat?.userName || '选择联系人' }}</h2>
          <span class="status-dot" :class="{ online: currentChat?.online }"></span>
        </div>
        <el-button type="success" :disabled="disabledFlag" @click="endAppointment"
                   v-if="currentChat&&(appointmentStatus == '1'||appointmentStatus == '5')">结束咨询
        </el-button>
      </div>

      <!-- 消息展示区域 -->
      <div class="message-list" ref="messageContainer">
        <div
            v-for="message in sortedMessages"
            :key="message.tempId || message.messageId"
            :class="['message-item', message.senderId === currentUser.id ? 'sent' : 'received']"
        >
          <img
              class="message-avatar"
              :src="getAvatar(message.senderId)"
              alt="avatar"
          />
          <div class="message-content">
            <p>{{ message.content }}</p>
            <span class="time">
              {{ formatTime(message.sendTime) }}
              <span v-if="message.status === 'sending'" class="status-icon">🕒</span>
              <span v-if="message.status === 'failed'" class="status-icon">❌</span>
            </span>
          </div>
        </div>
        <div v-if="appointmentStatus === '2'" class="consult-end-notice">
          <el-alert title="本次咨询已结束" type="info" center :closable="false"/>
        </div>
      </div>

      <!-- 消息输入区域 -->
      <div class="input-area" v-if="currentChat">
        <input
            v-model="newMessage"
            @keyup.enter="sendChatMessage"
            placeholder="输入消息..."
            :disabled="appointmentStatus === '2'"
        />
        <button @click="sendChatMessage" v-if="appointmentStatus !== '2'">发送</button>
      </div>
    </div>

    <div v-else class="empty-chat">
      <div class="empty-content">
        <el-icon :size="80" color="#b2e6d4">
          <ChatRound/>
        </el-icon>
        <p class="tip-text">暂时没有咨询，先来杯咖啡吧 ☕️</p>
      </div>
    </div>
  </div>

  <el-dialog title="咨询记录" v-model="open" append-to-body :show-close="false">
    <el-form ref="resultRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="主诉问题" prop="mainProblem">
        <el-input v-model="form.mainProblem" type="textarea" placeholder="请输入内容"
                  :autosize="{ minRows: 3, maxRows: 5}"/>
      </el-form-item>
      <el-form-item label="观察记录" prop="observation">
        <el-input v-model="form.observation" type="textarea" placeholder="请输入内容"
                  :autosize="{ minRows: 3, maxRows: 5}"/>
      </el-form-item>
      <el-form-item label="评估结果" prop="assessmentResult">
        <el-input v-model="form.assessmentResult" type="textarea" placeholder="请输入内容"
                  :autosize="{ minRows: 3, maxRows: 5}"/>
      </el-form-item>
      <el-form-item label="干预技术" prop="counselorMethod">
        <el-select v-model="form.counselorMethod" placeholder="请选择干预技术">
          <el-option
              v-for="dict in consult_techniques"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="其他疗法" prop="otherMethod" v-if="form.counselorMethod == '9'">
        <el-input v-model="form.otherMethod" type="textarea" placeholder="请输入内容"
                  :autosize="{ minRows: 3, maxRows: 5}"/>
      </el-form-item>
      <el-form-item label="进展" prop="progressEvaluation">
        <el-slider v-model="form.progressEvaluation" show-input placement="right"/>
      </el-form-item>
      <el-form-item label="风险评估" prop="riskAssessment">
        <el-select v-model="form.riskAssessment" placeholder="请选择风险评估">
          <el-option
              v-for="dict in risk_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="本次咨询用户满意度" prop="userSatisfaction">
        <el-input v-model="form.userSatisfaction" placeholder="请输入本次咨询用户满意度"/>
      </el-form-item>-->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">重 置</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import {getCurrentInstance, nextTick, onMounted, ref} from 'vue'
import {getHistoryMsg, getUserList} from "@/api/websocket/websocket.js";
import useUserStore from "@/store/modules/user.js";
import store from "@/store/index.js";
import dayjs from 'dayjs'
import {ElLoading} from "element-plus";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {useWebSocketStore} from '@/store/modules/websocket.js'
import {MessageType, SubType} from '@/constants/message'
import {ChatRound} from "@element-plus/icons-vue";
import {addAssessmentResult} from "@/api/result/result.js";
import {checkAppointmentStatus, end} from "@/api/appointment/appointment.js";

const {proxy} = getCurrentInstance()
const {
  consultation_type,
  consult_techniques,
  risk_level
} = proxy.useDict('consultation_type', 'consult_techniques', 'risk_level');

const wsStore = useWebSocketStore()
// 消息列表
const messages = computed(() => {
  if (!currentChat.value) return [];
  const participants = [
    Number(currentUser.value.id),
    Number(currentChat.value.userId)
  ].sort((a, b) => a - b)
  const chatId = participants.join('_')
  return wsStore.chatMessages.get(chatId) || [];
});

const messageContainer = ref(null)
// 输入框绑定
const newMessage = ref('')
// 联系人
const contactList = ref([])
// 当前聊天对象
const currentChat = ref(null)
// 上次点击联系人的id
const lastLoadedContactId = ref(null)
// 按钮禁用
const disabledFlag = ref(false)
// 对话框
const open = ref(false)
const appointmentStatus = ref('')

const data = reactive({
  form: {},
  rules: {
    mainProblem: [{required: true, message: '请输入主诉问题', trigger: 'blur'}],
    observation: [{required: true, message: '请输入观察记录', trigger: 'blur'}],
    assessmentResult: [{required: true, message: '请输入评估结果', trigger: 'blur'}],
    counselorMethod: [{required: true, message: '请选择干预疗法', trigger: 'blur'}],
    otherMethod: [{required: true, message: '请输入其他疗法', trigger: 'blur'}],
    progressEvaluation: [{required: true, message: '请选择进展', trigger: 'blur'}],
    riskAssessment: [{required: true, message: '请选择风险等级', trigger: 'blur'}],
  }
});

const {form, rules} = toRefs(data);

// 取消按钮
function cancel() {
  reset();
}

// 表单重置
function reset() {
  form.value = {
    resultId: null,
    userId: null,
    counselorId: null,
    startTime: null,
    endTime: null,
    counselorType: null,
    mainProblem: null,
    observation: null,
    assessmentResult: null,
    counselorMethod: null,
    otherMethod: null,
    progressEvaluation: 0,
    riskAssessment: null,
    userSatisfaction: null
  };
  proxy.resetForm("resultRef");
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["resultRef"].validate(valid => {
    if (valid) {
      addAssessmentResult(form.value, currentChat.value.userId, currentUser.value.id).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
      });
    }
  });
}

/** 结束咨询 */
const endAppointment = () => {
  disabledFlag.value = true;
  end(currentChat.value.userId, currentUser.value.id).then(res => {
    if (res.code == 200) {
      open.value = true;
      checkMethod(currentChat.value.userId, currentUser.value.id);
    }
  })
}

// 发送消息
const sendChatMessage = async () => {
  if (!newMessage.value.trim() || !currentChat.value) return;

  const messagePayload = {
    type: MessageType.CHAT_MSG,
    subType: SubType.CHAT.USER_TO_CONSULTANT,
    content: newMessage.value.trim(),
    receiverId: currentChat.value.userId,
  };

  // 清空输入前生成临时消息
  newMessage.value = '';

  // 通过 Store 发送
  await wsStore.sendMessage(messagePayload);
};

// 获取用户头像
const getAvatar = (id) => {
  // 优先从联系人列表获取
  const contact = contactList.value.find(user => user.userId === id)
  return contact?.avatar || currentUser.value.avatar
}

// 时间格式化
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

// 当前用户
const currentUser = computed(() => {
  const userStore = useUserStore(store)
  return {
    ...userStore,
    id: Number(userStore.id) // 确保数值类型
  }
})

// 消息排序
const sortedMessages = computed(() => {
  return [...messages.value].sort((a, b) =>
      new Date(a.sendTime) - new Date(b.sendTime)
  );
});

watch(sortedMessages, () => {
  nextTick(scrollToBottom)
})

watch(appointmentStatus, (newVal) => {
  if (newVal === '2') {
    // 自动滚动到底部显示提示
    nextTick(scrollToBottom)
    // 禁用结束按钮（根据模板逻辑会自动隐藏）
    disabledFlag.value = true
  }
})

watch(
    () => wsStore.currentAppointmentEnd,
    (newVal) => {
      if (newVal?.receiverId === currentUser.value.id &&
          newVal?.senderId === currentChat.value?.userId) {
        checkMethod(currentChat.value.userId, currentUser.value.id)
      }
    },
    {deep: true}
)

// 选择聊天对象时
const selectChat = (user) => {
  if (lastLoadedContactId.value === user.userId) {
    return;
  }
  currentChat.value = user
  lastLoadedContactId.value = user.id;
  nextTick(() => {
    document.querySelector('.input-area input')?.focus()
  })
  // 清空旧消息
  messages.value = []
  // 加载历史消息
  loadHistoryMsg();
  checkMethod(currentChat.value.userId, currentUser.value.id);
}
// 检查预约状态
const checkMethod = (patientId, counselorId) => {
  const actualPatientId = patientId || currentChat.value?.userId
  const actualCounselorId = counselorId || currentUser.value?.id

  if (!actualPatientId || !actualCounselorId) {
    console.warn('缺少必要参数，无法检查预约状态')
    return
  }
  checkAppointmentStatus(patientId, counselorId).then(res => {
    appointmentStatus.value = res.data;
    if (res.data === '2') {
      nextTick(scrollToBottom)
    }
  })
}

// 加载历史消息
async function loadHistoryMsg() {
  if (!currentChat.value) return;

  const loading = ElLoading.service({target: '.message-list'});
  try {
    const params = {
      pageNum: 1,
      pageSize: 1000,
      sortOrder: 'desc'
    };

    const res = await getHistoryMsg(
        currentUser.value.id,
        currentChat.value.userId,
        params
    );

    // 增加时间格式标准化
    const normalizeTime = (timeStr) => {
      return new Date(timeStr).toISOString();
    };

    const formattedMessages = res.rows.map(msg => ({
      ...msg,
      // 增加临时ID关联字段
      _clientTempId: msg.tempId ? msg.tempId.replace('client_', '') : null,
      sendTime: normalizeTime(msg.sendTime),
      isHistory: true,
      status: 'success'
    }));

    // 合并前处理重复
    const participants = [currentUser.value.id, currentChat.value.userId].sort();
    const chatId = participants.join('_');

    // 获取当前消息列表
    const currentMessages = wsStore.chatMessages.get(chatId) || [];

    // 创建映射：客户端临时ID -> 服务端消息
    const serverMsgMap = new Map();
    formattedMessages.forEach(msg => {
      if (msg._clientTempId) {
        serverMsgMap.set(msg._clientTempId, msg);
      }
    });

    const filteredCurrent = currentMessages.filter(currentMsg => {
      // 保留所有未完成消息
      if (currentMsg.status !== 'success') return true;

      // 实时消息不参与历史去重
      return !currentMsg.isHistory;
    });

    // 执行合并
    wsStore.mergeHistoryMessages(chatId, [...filteredCurrent, ...formattedMessages]);

    // 强制触发响应式更新
    wsStore.chatMessages = new Map(wsStore.chatMessages);

  } catch (error) {
    console.error('加载历史消息失败:', error);
  } finally {
    loading.close();
    await nextTick(scrollToBottom);
  }
}

// 滚动方法
const scrollToBottom = () => {
  if (messageContainer.value) {
    nextTick(() => {
      setTimeout(() => {
        messageContainer.value.scrollTo({
          top: messageContainer.value.scrollHeight,
          behavior: 'smooth'
        })
      }, 50)
    })
  }
}


watch(
    () => wsStore.chatMessages,
    () => {
      nextTick(scrollToBottom);
    },
    {deep: true}
);

// 获取所有联系人
function initChatList() {
  getUserList().then(res => {
    if (res) {
      contactList.value = res.rows;
    } else {

    }
  })
}

// 组件挂载时添加监听
onMounted(() => {
  initChatList();
});
</script>

<style scoped>

.message-list {
  display: flex;
  flex-direction: column;
  padding-bottom: 60px; /* 为提示留出空间 */
}

.consult-end-notice {
  margin-top: auto; /* 使提示紧贴底部 */
  position: sticky;
  bottom: 0;
  background: white;
  z-index: 1;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}

.consult-end-notice {
  padding: 20px;
  animation: fadeIn 0.5s;

  :deep(.el-alert) {
    background-color: #f4f4f5;
    border: 1px solid #e9e9eb;
    border-radius: 8px;
    width: 80%;
    margin: 0 auto;
  }
}

/* 禁用状态样式 */
.input-area input:disabled,
.input-area button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #f5f7fa;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

:deep(.dialog-footer) .el-form-item__content {
  margin-left: 0 !important;
  padding-top: 24px;
}

:deep(.dialog-footer) .el-button {
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.dialog-footer) .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.empty-state,
.empty-chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: rgba(255, 255, 255, 0.9);
}

.empty-chat {
  flex: 1;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9f5ff 100%);
}

.tip-text {
  margin-top: 16px;
  font-size: 16px;
  color: #7c8fa6;
  text-align: center;
  line-height: 1.5;
  max-width: 240px;
}

/* 左侧空状态动画 */
.empty-state .el-icon {
  animation: float 3s ease-in-out infinite;
}

/* 右侧聊天空状态 */
.empty-content {
  padding: 30px;
  border-radius: 16px;
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.chat-container {
  display: flex;
  height: 80vh;
  overflow: hidden;
}

/* 联系人列表样式 */
.contact-list {
  width: 320px;
  border-right: 2px solid #e0e0e0;
  box-shadow: 4px 0 6px -4px rgba(0, 0, 0, 0.1);
}

.list-title {
  padding: 16px;
  margin: 0;
  font-size: 18px;
  color: #333;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.contact-item:hover {
  background: #f5f5f5;
}

.contact-item.active {
  background: #e3f2fd;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2196f3;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.info h3 {
  margin: 0;
  font-size: 16px;
}

.last-msg {
  margin: 4px 0 0;
  color: #666;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.unread-badge {
  background: #ff4081;
  color: white;
  border-radius: 12px;
  padding: 2px 8px;
  font-size: 12px;
  margin-left: auto;
}

/* 聊天区域样式 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
  margin-left: 8px;
}

.status-dot.online {
  background: #4caf50;
}

/* 消息列表样式 */
.message-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  min-height: 0;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}

/* 接收消息样式 */
.message-item.received {
  justify-content: flex-start;
}

.message-item.received .message-avatar {
  order: 1;
  margin-right: 15px;
}

.message-item.received .message-content {
  order: 2;
  background: #f5f5f5;
  margin-left: 8px;
}

/* 发送消息样式 */
.message-item.sent {
  justify-content: flex-end;
}

.message-item.sent .message-avatar {
  order: 2;
  margin-left: 15px;
}

.message-item.sent .message-content {
  order: 1;
  background: #4ecb73;
  margin-right: 8px;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  max-width: 75%;
  padding: 12px 16px;
  border-radius: 15px;
  position: relative;
}

.time {
  font-size: 12px;
  color: #666;
  margin-top: 6px;
  display: block;
  text-align: right;
}

/* 输入区域样式 */
.input-area {
  position: sticky;
  display: flex;
  padding: 20px;
  border-top: 1px solid #eee;
  height: 60px;
  align-items: center;
  margin-top: auto;
  box-sizing: border-box;
}

.input-area input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  margin-right: 8px;
  height: 40px;
  transition: all 0.3s;
  font-size: 14px;
}

.input-area input:focus {
  border-color: #2196f3;
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
}

.input-area button {
  padding: 10px 20px;
  height: 40px;
  background: #2196f3;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.input-area button:hover {
  background: #1976d2;
}
</style>
